
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Token Authentication Page</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
  <div v-if="!isLoggedIn">
    <h2>Login</h2>
    <input type="text" v-model="username" placeholder="Username" required>
    <input type="password" v-model="password" placeholder="Password" required>
    <button @click="login">Login</button>
  </div>

  <div v-if="isLoggedIn">
    <h2>Welcome, {{ username }}!</h2>
    <p>This is protected content.</p>
    <button @click="logout">Logout</button>
  </div>
</div>

<script>new Vue({
  el: '#app',
  data: {
    username: '',
    password: '',
    isLoggedIn: false,
    token: ''
  },
  methods: {
    login() {
      const { username, password } = this;
      fetch('/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      })
      .then(response => response.json())
      .then(data => {
        if (data.token) {
          this.token = data.token;
          localStorage.setItem('token', this.token);
          this.isLoggedIn = true;
        } else {
          alert('Authentication failed. Please try again.');
        }
      })
      .catch(error => console.error('Error:', error));
    },
    logout() {
      localStorage.removeItem('token');
      this.token = '';
      this.isLoggedIn = false;
    }
  },
  created() {
    this.token = localStorage.getItem('token');
    if (this.token) {
      this.isLoggedIn = true;
    }
  }
});
</script>
</body>
</html>